// 用户状态管理模块
const state = {
  token: localStorage.getItem('token') || '',
  userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
  isLogin: !!localStorage.getItem('token')
}

const getters = {
  token: state => state.token,
  userInfo: state => state.userInfo,
  isLogin: state => state.isLogin,
  userId: state => state.userInfo.id,
  username: state => state.userInfo.username,
  nickname: state => state.userInfo.nickname,
  avatar: state => state.userInfo.avatar
}

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
    localStorage.setItem('token', token)
  },

  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
  },

  SET_LOGIN_STATUS(state, status) {
    state.isLogin = status
  },

  CLEAR_USER_DATA(state) {
    state.token = ''
    state.userInfo = {}
    state.isLogin = false
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }
}

const actions = {
  // 设置token
  setToken({ commit }, token) {
    commit('SET_TOKEN', token)
    commit('SET_LOGIN_STATUS', true)
  },

  // 设置用户信息
  setUserInfo({ commit }, userInfo) {
    commit('SET_USER_INFO', userInfo)
  },

  // 登录
  login({ commit }, { token, userInfo }) {
    commit('SET_TOKEN', token)
    commit('SET_USER_INFO', userInfo)
    commit('SET_LOGIN_STATUS', true)
  },

  // 登出
  logout({ commit }) {
    commit('CLEAR_USER_DATA')
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
} 